package com.study.zookeeper.curatorTest;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * curatorLock是一种可重用锁
 */
public class CuratorLockTest {
    private static String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
    private static int timeout = 2000;
    private static int sessionTimeout = 2000;
    /**
     * parame1:每隔多少毫秒进行重连
     * parame2:重连次数
     */
    private static RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000,3);

    public static void main(String[] args) {
        InterProcessMutex lock1 = new InterProcessMutex(getCuratorFramework(), "/locks");
        InterProcessMutex lock2 = new InterProcessMutex(getCuratorFramework(), "/locks");

        new Thread(new Runnable() {
            public void run() {
                try {
                    lock1.acquire();
                    System.out.println(Thread.currentThread().getName()+"获取到锁");
                    lock1.acquire();
                    System.out.println(Thread.currentThread().getName()+"再次获取到锁");
                    lock1.release();
                    System.out.println(Thread.currentThread().getName()+"释放锁");
                    lock1.release();
                    System.out.println(Thread.currentThread().getName()+"再次释放锁");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "thread1").start();

        new Thread(new Runnable() {
            public void run() {
                try {
                    lock2.acquire();
                    System.out.println(Thread.currentThread().getName()+"获取到锁");
                    lock2.acquire();
                    System.out.println(Thread.currentThread().getName()+"再次获取到锁");
                    lock2.release();
                    System.out.println(Thread.currentThread().getName()+"释放锁");
                    lock2.release();
                    System.out.println(Thread.currentThread().getName()+"再次释放锁");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "thread2").start();

    }

    private static CuratorFramework getCuratorFramework() {
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(connectString)//连接主机地址
                .connectionTimeoutMs(timeout)//连接超时时间
                .sessionTimeoutMs(sessionTimeout)//session超时时间
                .retryPolicy(retryPolicy).build();//连接失败多少秒之后进行重连
        //启动客户端
        client.start();
        return client;
    }
}
